import { CameraView, CameraType, useCameraPermissions } from 'expo-camera';
import { useCallback, useRef, useState } from 'react';
import { StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import * as MediaLibrary from 'expo-media-library';
import { router, useFocusEffect } from 'expo-router';
import AsyncStorage from '@react-native-async-storage/async-storage';
import axios from 'axios';
import { Button, Toast } from '@ant-design/react-native';

export default function camera() {
    // 初始化摄像头方向为后置
    const [facing, setFacing] = useState<CameraType>('back');
    // 请求摄像头权限
    const [cameraPermission, requestCameraPermission] = useCameraPermissions();
    const [mediaLibraryPermission, requestMediaLibraryPermission] = MediaLibrary.usePermissions();
    const [cameraRef, setCameraRef] = useState<any>(null);

    // 权限加载中，不显示内容
    if (!cameraPermission || !mediaLibraryPermission) {
        return <View />;
    }

    // 没有摄像头权限执行
    if (!cameraPermission.granted) {
        return (
            <View style={styles.container}>
                {/* <Text style={styles.message}>需要获取摄像头权限</Text> */}
                <Button onPress={requestCameraPermission}>获取摄像头权限</Button>
            </View>
        );
    }

    // 没有媒体库权限执行
    if (!mediaLibraryPermission.granted) {
        return (
            <View style={styles.container}>
                {/* <Text style={styles.message}>需要获取媒体库权限</Text> */}
                <Button onPress={requestMediaLibraryPermission}>获取媒体库权限</Button>
            </View>
        );
    }

    // 反转摄像头
    function toggleCameraFacing() {
        setFacing(current => (current === 'back' ? 'front' : 'back'));
    }

    // 拍照
    async function takePicture() {
        if (cameraRef) {
            const photo = await cameraRef.takePictureAsync();
            console.log(photo); // 输出照片信息到控制台

            try {
                // 保存图片到相册
                const asset = await MediaLibrary.createAssetAsync(photo.uri);
                console.log('Photo saved to media library:', asset);

                const info = JSON.parse(await AsyncStorage.getItem('userInfo') || '{}');
                await AsyncStorage.setItem('userInfo', JSON.stringify({ ...info, image: photo.uri }));
                let obj = {
                    _id: info._id,
                    image: photo.uri
                }
                await axios.post('http://192.168.13.227:3000/hw/EditInfo', obj).then(async (res) => {
                    if (res.data.code == 200) {
                        router.push('/CameraRes')
                        await AsyncStorage.setItem('pic', photo.uri)
                    }
                })
            }
            catch (error) {
                console.error('Error saving user info:', error);
            }
        }
    }

    return (
        <View style={styles.container}>
            <CameraView style={styles.camera} ref={setCameraRef} facing={facing}>
                <View style={styles.buttonContainer}>
                    <Button type='primary' style={styles.button} onPress={toggleCameraFacing} >反转</Button>
                    <Button type='primary' style={styles.button} onPress={takePicture} >拍照</Button>
                </View>
            </CameraView>
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
    },
    message: {
        textAlign: 'center',
        paddingBottom: 10,
    },
    camera: {
        flex: 1,
    },
    buttonContainer: {
        flex: 1,
        flexDirection: 'row',
        margin: 50,
    },
    button: {
        flex: 1,
        alignSelf: 'flex-end',
        alignItems: 'center',
    },
    text: {
        fontWeight: 'bold',
        color: 'white',
    },
});